<?php

namespace App\Http\Controllers\Site;

use App\B2BProject\Custom\Business\Invoice;
use App\B2BProject\Custom\Business\Order;
use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Custom\MemberInformation;
use App\B2BProject\Custom\Purchaser\ShoppingCart;
use App\B2BProject\Custom\Purchaser\ValueAddedTaxInvoiceQualification;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\B2BProject\Site\HelperControllerBuildTrait;
use App\B2BProject\Custom\Business\Address;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\Eloquent\ModelNotFoundException;

class OrderShoppingController extends Controller
{

    use HelperControllerBuildTrait;

    public function getIndex()
    {
        $orderInfo = Order::where('member_id', '1')->get();

        return view('host/order/createorder')->with('orderInfo', $orderInfo);
    }

    public function getSureOder()
    {
        return view('host/order/sureorder')->with('buy', 0);
    }


    /**
     * 获取当前用户的收货信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInfo()
    {
        $member = \Auth::user();
        $tt     = [];
        foreach (Address::where('member_id', $member->id)->get() as $add) {

            $item['id']   = $add->id;
            $item['tel']  = $add->tel_phone;
            $item['addr'] = $add->detail_area;
            $item['name'] = $add->name;
            $tt[]         = $item;
        }
        $data['data'] = $tt;
        return response()->json($data);

    }

    /**
     * 删除收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteAddr(Request $request)
    {

        $addrid       = $request->input('addrid');
        $affectedRows = Address::findOrFail($addrid)->delete();
        return response()->json($affectedRows);
    }


    /**
     * 保存新的收货信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function postReceiptInformation(Request $request)
    {
        $member = \Auth::user();
        try {
            \DB::transaction(function () use ($request, $member) {

                $validator = Validator::make($request->all(), [
                    'receieName' => 'required', // 姓名
                    'detailAddr' => 'required', // 详细地址
                    'mobTel'     => 'required', // 手机
                    'province'   => 'required|exists:areas,id,level,1',
                    'city'       => 'required|exists:areas,id,level,2',
                    'country'     => 'required|exists:areas,id,level,3'

                ]);
                if ($validator->fails()) {
                    return redirect()->back();
                }

                $data         = [
                    'name'        => $request->input('receieName'),
                    'member_id'   => $member->id,
                    'detail_area' => $request->input('detailAddr'),
                    'mob_phone'   => $request->input('mobTel'),
                    'province_id' => $request->input('province'),
                    'city_id'     => $request->input('city'),
                    'county_id'   => $request->input('country'),
                ];
                $data['code'] = 1;

                $address = Address::create($data)->save();
            });
            $tt = [];
            foreach (Address::where('member_id', $member->id)->get() as $add) {

                $item['id']   = $add->id;
                $item['tel']  = $add->mob_phone;
                $item['addr'] = $add->detail_area;
                $item['name'] = $add->name;
                $tt[]         = $item;
            }
            $da['data'] = $tt;
            return response()->json($da);

        } catch (ModelNotFoundException $e) {
            throw($e);
        }
    }

    /**
     * 获取发票信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getInvoiceInfo()
    {
        $member = \Auth::user();
        foreach (Invoice::where('member_id', $member->id)->get() as $invoice) {

            $item['id']   = $invoice->id;
            $item['name'] = $invoice->subject;
            $item['type'] = $invoice->type;
            $tt[]         = $item;
        }
        $data['data'] = $tt;
        return response()->json($data);
    }

    /**
     * 删除发票信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteInvoiceInfo(Request $request)
    {

        $invoice      = $request->input('invoiceid');
        $affectedRows = Invoice::findOrFail($invoice)->delete();
        return response()->json($affectedRows);
    }

    /**
     * 显示增值发票资质信息
     * @return mixed
     */
    public function getInvoice()
    {
        $member = \Auth::user();

        $invoice = Address::where('member_id', $member->id)->first();

        return $invoice;
    }


    /**
     * 保存发票信息
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function postSaveInvoice(Request $request)
    {
        $member = \Auth::user();
        //添加
        try {
            \DB::transaction(function () use ($request, $member) {
                // 发票抬头:  0-个人, 1-单位;
                if ($request->input('invoiceType') == 0) {
                    /*
                     if($request->input('invoiceTitle') ==0){

                     }else{

                     }*/
                    $invoice      = [
                        'member_id' => $member->id,
                        'type'      => '1',
                        'subject'   => $request->input('companyName'),
                    ];
                    $orderShpping = Invoice::create($invoice)->save();

                } else {

                    $data = [
                        'member_id'        => $member->id,
                        'company_name'     => $request->input('companyName'),
                        'code'             => $request->input('taxpayerCode'),
                        'address'          => $request->input('registAddr'),
                        'phone'            => $request->input('registTel'),
                        'bank'             => $request->input('bank'),
                        'bank_account'     => $request->input('bankCard'),
                        'bill_to_name'     => $request->input('receiverName'),
                        'bill_to_address'  => $request->input('detailAddr'),
                        'bill_to_phone'    => $request->input('mobile'),
                        'bill_to_province' => $request->input('province'),
                    ];
                    if (is_null($VAT = $member->VAT)) {
                        $VAT = ValueAddedTaxInvoiceQualification::create($data);
                    } else {
                        $VAT = $VAT->update($data);
                    }
                    $orderShpping = $member->VAT()->save($VAT);
                }
            });

            foreach (Invoice::where('member_id', $member->id)->get() as $invoice) {

                $item['id']   = $invoice->id;
                $item['name'] = $invoice->subject;
                $item['type'] = $invoice->type;
                $tt[]         = $item;
            }
            $data['data'] = $tt;
            return response()->json($data);

        } catch (ModelNotFoundException $e) {
            return response('error', 500);
            throw($e);
        }


    }

    /**
     * 获取商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Illuminate\View\View
     */
    public function getShopList(Request $request)
    {
        $member = \Auth::user();
        try {

            if ($request->input('buy') == 1) {
                $shoppingList =
                    ShoppingCart::where('member_id', $member->id)->orderBy('created_at', 'desc')->take(1)->get();
            } else {
                $shoppingList = ShoppingCart::where('member_id', $member->id)->get();
            }
            $count = ShoppingCart::where('member_id', $member->id)->count();
            $class = [];
            $total = 0;

            foreach ($shoppingList as $shop) {
                //根据goods_id 查找store_id
                $store_id = $shop->goods->store_id;

                if (!isset($class[$store_id])) {
                    //根据store_id 查找店铺的名字
                    $company = MemberInformation::where('id',
                        Store::where('id', $store_id)->first()->member_id)->first()->company;

                    $class[$store_id] = [
                        'storeid'   => $store_id,
                        'storeName' => $company
                    ];
                }
                $class[$store_id]['goodsList'][] = call_user_func_array(function (ShoppingCart $shop) use (&$total) {
                    $shops['goodid']   = $shop->goods_id;
                    $shops['href']     = route('goods.detail', [$shop->goods_id]);
                    $shops['img']      = $shop->goods->cover();
                    $shops['goodName'] = $shop->goods->name;
                    if ($shop->goods_spec_id) {
                        $shops['format'] = GoodsSpecification::where('id', $shop->goods_spec_id)->first()->spec_first;
                    }
                    $shops['price']  =
                        sprintf("%.2f", $shop->goods->original_price * $shop->goods->getPriceStrategy());
                    $shops['amount'] = $shop->amount;
                    $shops['total']  = sprintf("%.2f", $shops['amount'] * $shops['price']);

                    $total += ($shops['amount'] * $shops['price']);

                    return $shops;
                }, [$shop]);

                $data['data']['storeList'] = array_values($class);
            }
            $data['data']['totalPrice'] = $total;
            $data['data']['shopCart']   = route('cart.cart-list');
            return response()->json($data);

        } catch (UserTypeException $e) {
            return redirect('error', '403');
            throw $e;
        }
    }


    /**
     * 生成订单信息
     * @return $this
     */
    public function postCreateOrder(Request $request)
    {

        $storeName = $request->input('store_ids') . '_txt';
        $message   = $request->input($storeName);
        $addr      = $request->input('addr');
        $invoice   = $request->input('invoice-item');

        //TODO try catch
        $member = \Auth::user();

        $address = Address::where('member_id', $member->id)->where('id', $addr)->first();
        $invoice = Invoice::where('member_id', $member->id)->where('id', $invoice)->first();

        //立即购买
        if ($request->input('buy')) {
            $cart      = ShoppingCart::where('member_id', $member->id)->orderBy('created_at', 'desc')->first();
            $orderInfo = Order::createOrder($cart, $address, $invoice);
            return view('host/order/createorder')->with('orderInfo', $orderInfo);
        } else {
            //购物车
            $orderInfo = Order::createOrderFromShoppingCart($address, $invoice, $message);
            return view('host/order/createorder')->with('orderInfo', $orderInfo);
        }

    }

    /**
     * 直接生成订单
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function postShoppingOrder(Request $request)
    {
        $member = \Auth::user();
        //先加入购物车
        try {
            $validator = \Validator::make(
                $request->all(),
                [
                    'buyNum' => "required|numeric",
                ]
            );
            if ($validator->fails()) {
                return redirect()->back()->withErrors($validator);
            }
            \DB::transaction(function () use ($request,$member) {
                $data             = [];
                $data['goods_id'] = $request->input('goodsId');
                if ($request->input('shopSpecId')) {
                    $data['goods_spec_id'] = $request->input('shopSpecId');
                } else {
                    $data['goods_spec_id'] = '';
                }
                $data['amount'] = $request->input('buyNum');
                if(!ShoppingCart::where('member_id', $member->id)->orderBy('created_at', 'desc')->first()){
                    ShoppingCart::addToCart($data['goods_id'], $data['amount'], $data['goods_spec_id']);
                }
            });
            //立即购买页面
            return view('host/order/sureorder')->with('buy', $request->input('buy'));

        } catch (UserTypeException $e) {
            return redirect('error', '403');
            throw $e;
        }


    }

}
